package zh.demo.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import zh.demo.dao.*;
import zh.demo.model.*;
import zh.demo.utils.MaptoEntityUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("articleService")
public class ArticleService {
	@Autowired
	private ArticleDao articleDao;

	@Autowired
	RestTemplate restTemplate;

	@Autowired
	private AdOperationLogDao adOperationLogDao;

	@Autowired
	private AdDao adDao;

	@Autowired
	private ArticleClcikDao articleClcikDao;

	@Autowired
	private ArticleForwardDao articleForwardDao;

	public ArticleEntity queryObject(Long id){
		Map<String, Object> map = new HashMap<>();
		map.put("id",id);
		ArticleEntity entity = articleDao.selectArticle(map);
		return entity;
		//return articleDao.queryObject(id);
	}

	public List<ArticleEntity> queryList(Map<String, Object> map){
		return articleDao.queryList(map);
	}

	public List<Map<String, Object>> selectPublicArticleList(Map<String, Object> map){
		return articleDao.selectPublicArticleList(map);
	}

	public int queryTotal(Map<String, Object> map){
		return articleDao.queryTotal(map);
	}

	public Map<String, Object> selectArticleById(Long id){
		ArticleEntity articleEntity = articleDao.queryObject(id);
		List<AdEntity> adlist = adDao.selectAdByArticleId(id);
		Map<String, Object> map = new HashMap<>();
		map.put("article",articleEntity);
		map.put("adlist", adlist);
		return map;
	}

	@Transactional
	public Map<String, Object> save(/*ArticleEntity article, String userId, JSONObject jsonObject*/ ArticleEntity article){
		//ArticleEntity article = jsonObject.getObject("article", ArticleEntity.class);
		Long userId = article.getAuthor();//jsonObject.getString("userId");
		//JSONArray array = jsonObject.getJSONArray("ad");
		//AdEntity adEntity = jsonObject.getObject("ad", AdEntity.class);
		Map<String, Object> map = new HashMap<>();
		ResponseEntity<Map> userRes = restTemplate.getForEntity("http://user/api/info/"+userId, Map.class);
		Map<String, Object> res = userRes.getBody();
		UserEntity user = new UserEntity();
		try {
			MaptoEntityUtils.MaptoObject((LinkedHashMap<Object, Object>)res.get("user"), user);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

		BigDecimal articleAdMoney = article.getAdMoney();
		if(null!=articleAdMoney&&articleAdMoney.compareTo(user.getAdMoney())==1){//articleAdMonty 大于 user.getAdMoney
			BigDecimal lesAADmoney = articleAdMoney.subtract(user.getAdMoney());
			if(user.getFreeMoney().compareTo(lesAADmoney)==1){//如果可提现金额大于文章广告费减去用户广告费结余的金额，则修改用户账号金额
				user.setAdMoney(new BigDecimal(0));
				user.setFreeMoney(user.getFreeMoney().subtract(lesAADmoney));
				restTemplate.postForObject("http://uesr/api/save", user, null);
			}else{
				map.put("code",1);
				map.put("msg", "用户账号广告费金额不足，请充值");
				return map;
			}
		}else{
			BigDecimal adm = user.getAdMoney();
			//用户广告金额大于0
			if(null!=adm&&adm.compareTo(BigDecimal.ZERO)==1){
				BigDecimal lesAADmoney = user.getAdMoney().subtract(articleAdMoney);
				user.setAdMoney(lesAADmoney);
				restTemplate.postForObject("http://uesr/api/save", user, null);
			}

		}
		articleDao.saveByDynamicCol(article);
		/*Long articleId = article.getId();
		for (Object o : array) {
			//JSONObject json = (JSONObject) o;
			AdEntity adEntity = (AdEntity) o;
			adEntity.setArticleId(articleId);
			adDao.saveByDynamicCol(adEntity);
		}*/
		return map;
	}

	/**
	 * 分享文章广告(转发，点赞, 阅读，分享。。。)
	 * @param articleId
	 * @param type
	 * @param adId
	 * @param userId
	 * @param ip
	 * @param province
	 * @param city
	 * @param district
	 */
	public Map<String, Object> shareArticle(Long articleId, String type, Long adId, Long userId,
							 String ip, String province, String city, String district){
		Map<String, Object> resmap = new HashMap<>();
		Calendar ca = Calendar.getInstance();
		ArticleEntity articleEntity = articleDao.queryObject(articleId);
		ResponseEntity<Map> userRes = restTemplate.getForEntity("http://user/api/info/"+userId, Map.class);
		Map<String, Object> res = userRes.getBody();
		UserEntity user = new UserEntity();
		try {
			MaptoEntityUtils.MaptoObject((LinkedHashMap<Object, Object>)res.get("user"), user);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		//0:阅读, 1:转发，2:点赞，3:点击广告
		AdOperationLogEntity adOperationLogEntity = new AdOperationLogEntity();
		if(type.equals("0")){
			articleEntity.setClickCount(articleEntity.getClickCount()+1);

			//阅读表插入一条记录
			adOperationLogEntity.setArticleId(articleId);
			//操作类型参照数据字典表sys_dict
			adOperationLogEntity.setOperation("articlead01");//查看，阅读
			adOperationLogEntity.setType("articleadtype01");//操作文章

		}else if(type.equals("1")){
			articleEntity.setForwardCount(articleEntity.getForwardCount()+1);

			//操作类型参照数据字典表sys_dict
			adOperationLogEntity.setOperation("articlead02");//转发
			adOperationLogEntity.setType("articleadtype01");//操作文章

			Map<String, Object> map = new HashMap<>();
			map.put("userId",userId);
			map.put("articleId",articleId);
			AdOperationLogEntity adop = adOperationLogDao.selectArticleOperationRecode(map);
			if(adop==null) {
				//给当前转发广告用户可结算金额增加转发一次文章的佣金
				articleEntity.setLeftAdMoney(articleEntity.getLeftAdMoney().subtract(articleEntity.getForwardMoney()));
				user.setFreeMoney(user.getFreeMoney().add(articleEntity.getForwardMoney()));
			}else{
				Date d1 = adop.getOperationTime();
				Date d2 = ca.getTime();
				long timess = d2.getTime() - d1.getTime();
				String forwardRule = articleEntity.getForwardRule();
				if(articleEntity.getLeftAdMoney().compareTo(articleEntity.getForwardMoney())==1){
					if("forwardrule01".equals(forwardRule)){
						if(timess>1000*60*60*12){
							articleEntity.setLeftAdMoney(articleEntity.getLeftAdMoney().subtract(articleEntity.getForwardMoney()));
							user.setFreeMoney(user.getFreeMoney().add(articleEntity.getForwardMoney()));
						}
					}else if("forwardrule02".equals(forwardRule)){
						if(timess>1000*60*60*24){
							articleEntity.setLeftAdMoney(articleEntity.getLeftAdMoney().subtract(articleEntity.getForwardMoney()));
							user.setFreeMoney(user.getFreeMoney().add(articleEntity.getForwardMoney()));
						}
					}
					resmap.put("code",0);
				}else{
					resmap.put("code",1);
					resmap.put("msg","广告费余额不足支付转发佣金，请联系广告主充值！");
				}
			}

		}else if(type.equals("2")){
			adOperationLogEntity.setOperation("articlead03");//点赞
			adOperationLogEntity.setType("articleadtype01");//操作文章

		}else if(type.equals("3")){
			adOperationLogEntity.setOperation("articlead04");//点击广告
			adOperationLogEntity.setType("articleadtype02");//操作广告
			Map<String, Object> map = new HashMap<>();
			map.put("userId",userId);
			map.put("articleId",articleId);
			AdOperationLogEntity adop = adOperationLogDao.selectArticleOperationRecode(map);
			if(adop==null) {
				if(articleEntity.getLeftAdMoney().compareTo(articleEntity.getClickMoney())==1){
					articleEntity.setLeftAdMoney(articleEntity.getLeftAdMoney().subtract(articleEntity.getClickMoney()));

					//给当前转发广告用户可结算金额增加点击一次广告的佣金
					user.setFreeMoney(user.getFreeMoney().add(articleEntity.getClickMoney()));
					resmap.put("code",0);
				}else{
					resmap.put("code",1);
					resmap.put("msg","广告费余额不足支付点击广告佣金，请联系广告主充值！");
				}
			}
		}

		if(null!=ip){
			adOperationLogEntity.setIp(ip);
		}
		adOperationLogEntity.setUserId(userId);
		adOperationLogEntity.setUsername(user.getUsername());
		adOperationLogEntity.setRealname(user.getRealname());
		adOperationLogEntity.setProvince(province);
		adOperationLogEntity.setCity(city);
		adOperationLogEntity.setDistrict(district);
		adOperationLogEntity.setSex(user.getSex());
		adOperationLogEntity.setTelphone(user.getMobile());
		adOperationLogDao.saveByDynamicCol(adOperationLogEntity);
		articleDao.update(articleEntity);
		restTemplate.postForObject("http://uesr/api/update", user, null);
		return resmap;
	}

	/**
	 * 审核文章
	 * @param articleId
	 * @param userId
	 * @param status
	 */
	public void verifyArticle(String articleId, String userId, String status){
		//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar ca = Calendar.getInstance();
		ArticleEntity articleEntity = articleDao.queryObject(articleId);
		ResponseEntity<Map> userRes = restTemplate.getForEntity("http://user/api/info/"+userId, Map.class);
		Map<String, Object> res = userRes.getBody();
		UserEntity user = new UserEntity();
		try {
			MaptoEntityUtils.MaptoObject((LinkedHashMap<Object, Object>)res.get("user"), user);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		articleEntity.setAuditor(user.getUsername());
		articleEntity.setAuditTime(ca.getTime());
		articleEntity.setStatus(status);
		articleDao.update(articleEntity);
	}


	public void update(ArticleEntity article){
		articleDao.update(article);
	}

	public void delete(Long id){
		articleDao.delete(id);
	}

	public void deleteBatch(Long[] ids){
		articleDao.deleteBatch(ids);
	}



	
}
